layui.use(['table', 'ax','laydate','admin'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var laydate = layui.laydate;
    var admin = layui.admin;
    lay('.datetime-input').each(function(){
        laydate.render({
            elem: this
            ,trigger: 'click'
            ,type: 'datetime'
        });
    });

    /**
     * 字典类型表管理
     */
    var WechatUser = {
        tableId: "wechatUserTable"
    };

    /**
     * 初始化表格的列
     */
    WechatUser.initColumn = function () {
        return [[
            {type: 'checkbox',fixed:"left"},
            {type:'numbers',title:"序号",fixed:"left"},
            {field: 'id', hide: true, title: '编号'},
            //{field:'mp_code',sort:true,title:"账号类别",fixed:'left',templet:function(d){ return d.mpCode==""?"未知":(d.mpCode.indexOf("mp_")>=0?"公众号":"小程序")}},
            {field: 'userNo', sort: true, title: '用户编号',fixed:'left'},
            {field:'userName',sort:true,title:'姓名'},
            {field:'area',title:'所在区域',templet(d){return _.defaultTo(d.area,"未设置")}},
            {field:'remark',title:'住址'},
            {field: 'wechatNickName', sort: true, title: '昵称',width:""},
            {field: 'withdraw',title:"积分",templet:function(d){return d.withdraw}},
            {field:'status',title:'状态',templet:function(d){return _.defaultTo(d.statusModel.name,"--")}},
            {field:'userBins',title:"用户回收桶"},
            {field: 'createTime', sort: true, title: '创建时间'},
            {align: 'center', toolbar: '#tableBar', title: '操作',fixed:"right",minWidth:120}
        ]];
    };

    /**
     * 点击查询按钮
     */
    WechatUser.search = function () {
        var queryData = {};
        queryData['openId'] = $("#openId").val();
        queryData['wechatNickName'] = $("#wechatNickName").val();
        queryData['accountName'] = $("#accountName").val();
        queryData['userNo'] = $("#userNo").val();
        queryData['area'] = $("#area").val();
        queryData['createTime'] = $("#createTime").val();
        queryData['remark'] = $("#remark").val();
        queryData['phone'] = $("#phone").val();
        queryData['userName'] = $("#userName").val();
        queryData['email'] = $("#email").val();
        queryData['sex'] = $("#sex").val();
        queryData['birthDay'] = $("#birthDay").val();
        queryData['age'] = $("#age").val();
        queryData['userId'] = $("#userId").val();
        queryData['deviceInfo'] = $("#deviceInfo").val();
        queryData['deviceId'] = $("#deviceId").val();
        table.reload(WechatUser.tableId, {where: queryData});
    };

    /**
     * 弹出添加对话框
     */
    WechatUser.openAddDlg = function () {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '添加微信账号',
            content: Feng.ctxPath + '/wechatUser/add',
            area:"750px",
            end: function () {
                admin.getTempData('formOk') && table.reload(WechatUser.tableId);
            }
        });
    };

    /**
     * 导出excel按钮
     */
    WechatUser.exportExcel = function () {
        var checkRows = table.checkStatus(WechatUser.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };
    WechatUser.delItems = function () {
        var checkRows = table.checkStatus(WechatUser.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要删除的数据");
        } else {
            var datas = checkRows.data;
            var params = [];
            for(var i=0;i<datas.length;i++){
                params.push(datas[i].id);
            }
            var paramsJson = JSON.stringify(params);
            $.ajax({
                type:"POST",
                url: Feng.ctxPath + "/wechatUser/delItems",
                dataType:"json",
                contentType:"application/json", // 指定这个协议很重要
                data:paramsJson,
                async:false,
                //只有这一个参数，json格式，后台解析为实体，后台可以直接用
                success:function(data){
                    Feng.success("删除成功!");
                    table.reload(WechatUser.tableId);
                }
            })


        }
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    WechatUser.openEditDlg = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '修改微信账号',
            area:"750px",
            content: Feng.ctxPath + '/wechatUser/edit?id=' + data.id,
            end: function () {
                admin.getTempData('formOk') && table.reload(WechatUser.tableId);
            }
        });
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    WechatUser.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/wechatUser/delete", function (data) {
                if(data.success){

                    Feng.success("删除成功!");
                    table.reload(WechatUser.tableId);
                }else{
                    Feng.error(data.message);
                }
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + WechatUser.tableId,
        url: Feng.ctxPath + '/wechatUser/list',
        page: true,
        height: "full-98",
        cellMinWidth: 100,
        cols: WechatUser.initColumn(),
        done: function(res, curr, count){
            console.table(res);
        }
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        var validation = new Validation($("form")[0], {onSubmit:false});
        var validate = validation.validate();
        if(validate){
            WechatUser.search();
        }else{
            var serializeArray = $(".validation-failed");
            var errMsgs = "";
            for(var i=0;i<serializeArray.length;i++){
                var elemInfo = serializeArray[i];
                var elem = $("#"+elemInfo.name)[0];
                if(elem && elem.tooltip){
                    errMsgs+="<div><span style='color:dodgerblue'>"+elem.placeholder+"输入框有误：</span><span style='color:red'>"+elem.tooltip.content+"</span></div>"
                    var tipElem = elem.tagName=="SELECT"?$(elem).next():elem;
                    layer.tips(elem.tooltip.content,tipElem,{
                        tips: [1, '#FF99CC'],
                        time: 4000,
                        tipsMore: true
                    });
                }
            }
            //Feng.error(errMsgs);
        }
        return false;
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        WechatUser.openAddDlg();
        return false;
    });
    // 导出excel
    $('#btnExp').click(function () {
        WechatUser.exportExcel();
        return false;
    });
    $('#btnDel').click(function () {
        WechatUser.delItems();
        return false;
    });
    $("#showQrcode").click(function(){
        var checkRows = table.checkStatus(WechatUser.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择用户");
        } else {
            var userId = checkRows.data[0].id;
            window.location.href=Feng.ctxPath+"/wechatUser/show_qrcode?id="+userId;
        }
        return false;
    })
    $("#btnExchange").click(function(){
        var checkRows = table.checkStatus(WechatUser.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择用户");
        } else {
            var userId = checkRows.data[0].id;
            console.log("选中用户："+userId);
            //window.location.href=Feng.ctxPath+"/wechatUser/showExchange?id="+userId;
            admin.putTempData('formOk', false);
            top.layui.admin.open({
                type:2,
                title:'兑换商品',
                content:Feng.ctxPath+"/wechatUser/showExchange?id="+userId,
                end:function(){
                    admin.getTempData('formOk') && table.reload(WechatUser.tableId);
                }
            })
        }
        return false;
    })
    WechatUser.onShow = function(data){
        top.layui.admin.open({
            type: 2,
            title: '查看微信账号',
            content: Feng.ctxPath + '/wechatUser/show?id=' + data.id,
        });
    }

    // 工具条点击事件
    table.on('tool(' + WechatUser.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            WechatUser.openEditDlg(data);
        } else if (layEvent === 'delete') {
            WechatUser.onDeleteItem(data);
        }else if(layEvent==='show'){
            WechatUser.onShow(data);
        }
    });
});
